"""查找运行中的后端服务器 - 扫描所有可能的端口."""
import socket
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed

print("=" * 60)
print("查找运行中的后端服务器")
print("=" * 60)
print()

def check_port(port):
    """检查端口是否被占用."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.5)
    result = sock.connect_ex(('localhost', port))
    sock.close()
    return result == 0

def check_api(port):
    """检查是否是 FastAPI 服务器."""
    try:
        response = requests.get(f"http://localhost:{port}/docs", timeout=2)
        return response.status_code == 200
    except:
        return False

# 扫描端口范围
print("步骤 1: 扫描端口 8000-8020...")
open_ports = []

for port in range(8000, 8021):
    if check_port(port):
        open_ports.append(port)
        print(f"✅ 端口 {port} 被占用")

if not open_ports:
    print("❌ 未找到占用的端口")
    print()
    print("建议:")
    print("   cd backend")
    print("   python smart_start.py")
else:
    print()
    print("=" * 60)
    print("步骤 2: 检查是否为 FastAPI 服务器...")
    print("=" * 60)
    print()

    fastapi_servers = []

    for port in open_ports:
        print(f"检查端口 {port}...", end=" ")
        if check_api(port):
            print("✅ FastAPI 服务器!")
            fastapi_servers.append(port)
        else:
            print("❌ 非 FastAPI 服务器")

    if fastapi_servers:
        print()
        print("=" * 60)
        print("✅ 找到 FastAPI 服务器!")
        print("=" * 60)
        print()

        for port in fastapi_servers:
            print(f"🌐 服务器地址: http://localhost:{port}")
            print(f"📚 API 文档: http://localhost:{port}/docs")
            print()

            # 测试新的 API 端点
            print(f"   测试 MVP1 端点:")
            endpoints = [
                "/api/v1/stats/quality-distribution",
                "/api/v1/stats/priority-followups",
            ]

            for endpoint in endpoints:
                url = f"http://localhost:{port}{endpoint}"
                print(f"   - {endpoint}...", end=" ")
                try:
                    # 不带认证测试（可能返回401但说明端点存在）
                    response = requests.get(url, timeout=2)
                    if response.status_code == 401:
                        print("✅ 存在（需要认证）")
                    elif response.status_code == 200:
                        print("✅ 可访问")
                    else:
                        print(f"⚠️ HTTP {response.status_code}")
                except Exception as e:
                    print(f"❌ 错误")

            print()

        print("=" * 60)
        print("📌 下一步操作:")
        print("=" * 60)
        print(f"1. 访问 http://localhost:{fastapi_servers[0]}/docs")
        print("2. 使用 test_mvp1_api.html 测试 API")
        print("3. 访问前端 Dashboard 查看「今日优先跟进」卡片")
        print()

    else:
        print()
        print("❌ 未找到 FastAPI 服务器")
        print()
        print("虽然发现端口被占用，但不是 FastAPI 服务器")
        print("建议重新启动:")
        print("   cd backend")
        print("   python smart_start.py")
